import Toast from 'tdesign-miniprogram/toast/index';
import { getOutfitDetail, createOutfit, updateOutfit, uploadOutfitImage, getOccasionList, addOccasion } from '../../../services/outfit/outfit';
import clothesData from '../../../data/clothesData';

Page({
  data: {
    id: '',
    name: '',
    image: '',
    seasons: [], // 改为数组，支持多选
    occasions: [], // 改为数组，支持多选
    note: '',
    clothes: [],
    seasonOptions: [
      { label: '春季', value: '春', isSelected: false },
      { label: '夏季', value: '夏', isSelected: false },
      { label: '秋季', value: '秋', isSelected: false },
      { label: '冬季', value: '冬', isSelected: false }
    ],
    occasionOptions: [], // 场合选项列表，将添加 isSelected 属性
    showInlineAddOccasionInput: false, // 控制内联添加场合输入区域的显示
    newOccasion: '',
    loading: false,
    showClothesSelector: false,
    allClothes: [], // 存储所有衣物数据
    searchValue: '', // 搜索关键词
    currentSeason: '', // 当前选中的季节（用于衣物筛选）
    currentCategory: '', // 当前选中的分类（用于衣物筛选）
    clothesCategoryOptions: [], // 新增：衣物分类选项列表
    currentStep: 1 // 当前步骤
  },

  onLoad(options) {
    this.loadOccasions();
    this.loadAllClothes(); // 先加载所有衣物

    if (options.id) {
      this.setData({ id: options.id });
      this.loadOutfitDetail();
    }

    // 确保衣物选择弹窗和内联输入区域初始为 false
    this.setData({
      showClothesSelector: false,
      showInlineAddOccasionInput: false
    });
  },

  onShow() {
    // 在 onShow 中也强制确保衣物选择弹窗和内联输入区域是关闭的
    this.setData({
      showClothesSelector: false,
      showInlineAddOccasionInput: false
    });
  },

  async loadOccasions() {
    try {
      const res = await getOccasionList();
      // 为每个场合选项添加 isSelected 属性
      const occasionOptionsWithStatus = res.data.map(item => ({
        ...item,
        isSelected: false
      }));
      this.setData({ occasionOptions: occasionOptionsWithStatus });
    } catch (error) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '加载场合列表失败',
        icon: 'error'
      });
    }
  },

  // 加载所有衣物数据
  loadAllClothes() {
    // 使用原始 clothesData 作为全部衣物数据源
    this.setData({
      allClothes: clothesData,
      filteredClothes: clothesData // 初始时不过滤
    });
    console.log('loadAllClothes: 加载所有衣物数据', this.data.allClothes);

    // 动态生成衣物分类选项列表，使用 item.type 作为 value
    const categories = [...new Set(clothesData.map(item => item.type).filter(Boolean))]; // 提取不重复的非空类型
    const clothesCategoryOptions = [
      { label: '全部', value: '' }, // 添加"全部"选项，value 为空字符串
      ...categories.map(cat => ({ label: cat, value: cat })) // 使用 type 作为 label 和 value
    ];
    this.setData({ clothesCategoryOptions });
    console.log('loadAllClothes: 生成衣物分类选项', this.data.clothesCategoryOptions);
  },

  // 过滤衣物列表
  filterClothes() {
    console.log('filterClothes: 开始过滤', { currentSeason: this.data.currentSeason, currentCategory: this.data.currentCategory, searchValue: this.data.searchValue });
    let filtered = [...this.data.allClothes];

    // 按季节筛选
    if (this.data.currentSeason) {
      filtered = filtered.filter(item => item.season && item.season.includes(this.data.currentSeason));
      console.log('filterClothes: 按季节过滤后', filtered.length);
    }

    // 按分类筛选 (使用 item.type)
    // 当 currentCategory 为空字符串时，表示选择"全部"，不进行分类过滤
    if (this.data.currentCategory !== '') {
      filtered = filtered.filter(item => item.type && typeof item.type === 'string' && item.type === this.data.currentCategory);
      console.log('filterClothes: 按分类过滤后', filtered.length);
    }

    // 按搜索关键词筛选
    if (this.data.searchValue) {
      const searchLower = this.data.searchValue.toLowerCase();
      filtered = filtered.filter(item => {
        const nameMatch = item.name && typeof item.name === 'string' && item.name.toLowerCase().includes(searchLower);
        const categoryMatch = item.type && typeof item.type === 'string' && item.type.toLowerCase().includes(searchLower); // 使用 item.type
        return nameMatch || categoryMatch;
      });
      console.log('filterClothes: 按搜索过滤后', filtered.length);
    }

    this.setData({ filteredClothes: filtered });
    console.log('filterClothes: 过滤完成，更新 filteredClothes', this.data.filteredClothes.length);
  },

  // 搜索输入
  onSearchInput(e) {
    console.log('onSearchInput: 搜索关键词', e.detail.value);
    this.setData({
      searchValue: e.detail.value
    });
    this.filterClothes();
  },

  // 清除搜索
  onSearchClear() {
    console.log('onSearchClear: 清除搜索');
    this.setData({
      searchValue: ''
    });
    this.filterClothes();
  },

  // 选择季节 (多选)
  onSelectSeason(e) {
    const selectedValue = e.currentTarget.dataset.value;
    const seasonOptions = [...this.data.seasonOptions];

    const targetOption = seasonOptions.find(item => item.value === selectedValue);
    if (targetOption) {
      targetOption.isSelected = !targetOption.isSelected; // 切换选中状态
    }

    // 更新 seasons 数组（用于保存和验证）
    const seasons = seasonOptions.filter(item => item.isSelected).map(item => item.value);

    this.setData({
      seasonOptions: seasonOptions, // 更新选项列表，触发视图刷新
      seasons: seasons
    });
    console.log('onSelectSeason: 更新季节选中状态', seasons);
  },

  // 分类选择 (用于衣物选择器内的分类过滤)
  onCategorySelect(e) {
    const { value } = e.currentTarget.dataset;
    console.log('onCategorySelect: 选择分类', value);
    this.setData({
      currentCategory: value
    });
    this.filterClothes(); // 选择分类后立即过滤
  },

  async loadOutfitDetail() {
    try {
      const res = await getOutfitDetail(this.data.id);
      const outfit = res.data;

      // 根据加载的搭配详情设置季节和场合选项的选中状态
      const seasonOptions = this.data.seasonOptions.map(item => ({
        ...item,
        isSelected: outfit.seasons ? outfit.seasons.includes(item.value) : false
      }));
      const occasionOptions = this.data.occasionOptions.map(item => ({
        ...item,
        isSelected: outfit.occasions ? outfit.occasions.includes(item.value) : false
      }));

      this.setData({
        name: outfit.name,
        image: outfit.image,
        seasons: outfit.seasons || [], // 仍然保留 value 数组
        occasions: outfit.occasions || [], // 仍然保留 value 数组
        note: outfit.note || '',
        clothes: outfit.clothes || [],
        seasonOptions: seasonOptions, // 更新带状态的选项列表
        occasionOptions: occasionOptions // 更新带状态的选项列表
      });

      // 加载详情后也强制关闭衣物选择弹窗
      this.setData({ showClothesSelector: false });
    } catch (error) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '加载失败',
        icon: 'error'
      });
    }
  },

  onNameChange(e) {
    this.setData({ name: e.detail.value });
  },

  // 选择场合 (多选)
  onSelectOccasion(e) {
    const selectedValue = e.currentTarget.dataset.value;
    const occasionOptions = [...this.data.occasionOptions];

    const targetOption = occasionOptions.find(item => item.value === selectedValue);
    if (targetOption) {
      targetOption.isSelected = !targetOption.isSelected; // 切换选中状态
    }

    // 更新 occasions 数组（用于保存和验证）
    const occasions = occasionOptions.filter(item => item.isSelected).map(item => item.value);

    this.setData({
      occasionOptions: occasionOptions, // 更新选项列表，触发视图刷新
      occasions: occasions
    });
    console.log('onSelectOccasion: 更新场合选中状态', occasions);
  },

  onNoteChange(e) {
    this.setData({ note: e.detail.value });
  },

  // 选择衣物
  selectClothes(e) {
    const { clothes } = e.currentTarget.dataset;
    const currentClothes = [...this.data.clothes];

    // 检查是否已经选择过该衣物
    const exists = currentClothes.some(item => item.id === clothes.id);
    if (!exists) {
      currentClothes.push(clothes);
      this.setData({ clothes: currentClothes });
    }
    console.log('selectClothes: 选择衣物', clothes);
  },

  // 移除衣物
  removeClothes(e) {
    const { index } = e.currentTarget.dataset;
    const clothes = this.data.clothes.filter((_, i) => i !== index);
    this.setData({ clothes });
    console.log('removeClothes: 移除衣物，剩余', clothes.length);
  },

  showAddOccasion() {
    this.setData({
      showInlineAddOccasionInput: true, // 显示内联输入区域
      newOccasion: ''
    });
    console.log('showAddOccasion: 显示内联添加场合输入');
  },

  onNewOccasionChange(e) {
    this.setData({ newOccasion: e.detail.value });
  },

  async addNewOccasion() {
    if (!this.data.newOccasion.trim()) {
      Toast({
        context: this,
        selector: '#t-toast',
        message: '请输入场合名称',
        icon: 'error'
      });
      return;
    }

    try {
      // 模拟添加场合成功，实际应调用后端接口
      // const res = await addOccasion(this.data.newOccasion);

      // 模拟返回新场合的数据结构
      const newOccasionValue = this.data.newOccasion.trim();
      const res = { data: { label: newOccasionValue, value: newOccasionValue } };
      console.log('addNewOccasion: 模拟添加新场合返回', res.data);

      // 重新加载场合列表，确保数据最新
      await this.loadOccasions();
      console.log('addNewOccasion: 重新加载场合列表');

      // 自动选中新添加的场合
      const occasionOptions = this.data.occasionOptions.map(item => ({
        ...item,
        isSelected: this.data.occasions.includes(item.value) || item.value === res.data.value // 保持原有选中，并选中新添加的
      }));

      // 更新 occasions 数组，包含新添加并自动选中的场合
      const updatedOccasions = occasionOptions.filter(item => item.isSelected).map(item => item.value);
      console.log('addNewOccasion: 更新 occasions 数组', updatedOccasions);

      this.setData({
        occasionOptions: occasionOptions,
        occasions: updatedOccasions,
        showInlineAddOccasionInput: false, // 隐藏内联输入区域
        newOccasion: '' // 清空输入框
      });
      console.log('addNewOccasion: 数据更新完成');

    } catch (error) {
      console.error('addNewOccasion: 添加失败', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '添加失败',
        icon: 'error'
      });
    }
  },

  cancelAddOccasion() {
    this.setData({
      showInlineAddOccasionInput: false, // 隐藏内联输入区域
      newOccasion: '' // 清空输入框
    });
    console.log('cancelAddOccasion: 取消添加场合');
  },

  async chooseImage() {
    try {
      const res = await wx.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      });

      const tempFilePath = res.tempFilePaths[0];
      this.setData({ loading: true });

      // 模拟图片上传成功，实际应调用后端接口
      // const uploadRes = await uploadOutfitImage(tempFilePath);
      // this.setData({
      //   image: uploadRes.data.url,
      //   loading: false
      // });
      console.log('chooseImage: 模拟上传图片成功', tempFilePath);
      this.setData({
        image: tempFilePath, // 暂时使用本地路径显示
        loading: false
      });

    } catch (error) {
      this.setData({ loading: false });
      console.error('chooseImage: 上传失败', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '上传失败',
        icon: 'error'
      });
    }
  },

  // 步骤控制
  nextStep() {
    // 验证当前步骤
    if (!this.validateCurrentStep()) {
      console.log('nextStep: 验证失败，停止下一步');
      return;
    }

    // 进入下一步
    const next = this.data.currentStep + 1;
    this.setData({
      currentStep: next,
      // 确保在离开步骤2时关闭衣物选择器，在进入步骤2时不打开
      showClothesSelector: false // 明确在步骤切换时不默认打开衣物选择器
    });
    console.log('nextStep: 进入步骤', this.data.currentStep);
  },

  prevStep() {
    const prev = this.data.currentStep - 1;
    this.setData({
      currentStep: prev,
      // 确保在离开步骤2时关闭衣物选择器
      showClothesSelector: false // 明确在步骤切换时不默认打开衣物选择器
    });
    console.log('prevStep: 返回步骤', this.data.currentStep);
  },

  // 验证当前步骤
  validateCurrentStep() {
    console.log('validateCurrentStep: 验证步骤', this.data.currentStep);
    switch (this.data.currentStep) {
      case 1: // 基本信息
        if (!this.data.name) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请输入搭配名称',
            icon: 'error'
          });
          console.log('validateCurrentStep: 步骤1 验证失败 - 名称为空');
          return false;
        }
        if (this.data.seasons.length === 0) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请选择适用季节',
            icon: 'error'
          });
          console.log('validateCurrentStep: 步骤1 验证失败 - 季节未选择');
            return false;
        }
        if (this.data.occasions.length === 0) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请选择适用场合',
            icon: 'error'
          });
          console.log('validateCurrentStep: 步骤1 验证失败 - 场合未选择');
            return false;
        }
        console.log('validateCurrentStep: 步骤1 验证通过');
          return true;

      case 2: // 选择衣物
        if (this.data.clothes.length === 0) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请选择衣物',
            icon: 'error'
          });
          console.log('validateCurrentStep: 步骤2 验证失败 - 衣物未选择');
          return false;
        }
        console.log('validateCurrentStep: 步骤2 验证通过');
          return true;

      case 3: // 上传图片
        if (!this.data.image) {
          Toast({
            context: this,
            selector: '#t-toast',
            message: '请上传搭配图片',
            icon: 'error'
          });
          console.log('validateCurrentStep: 步骤3 验证失败 - 图片未上传');
          return false;
        }
        console.log('validateCurrentStep: 步骤3 验证通过');
          return true;

      default:
        return true;
    }
  },

  // 保存搭配
  async saveOutfit() {
    console.log('saveOutfit: 尝试保存搭配');
    if (!this.validateCurrentStep()) {
      return;
    }

    this.setData({ loading: true });

    try {
      // 准备要发送的数据
      const outfitData = {
        name: this.data.name,
        image: this.data.image,
        seasons: this.data.seasons,
        occasions: this.data.occasions,
        note: this.data.note,
        clothes: this.data.clothes
      };

      console.log('saveOutfit: 即将发送的数据:', outfitData);

      let res;
      if (this.data.id) {
        // 编辑现有搭配
        res = await updateOutfit(this.data.id, outfitData);
        console.log('saveOutfit: updateOutfit 服务调用成功');
      } else {
        // 创建新搭配
        res = await createOutfit(outfitData);
        console.log('saveOutfit: createOutfit 服务调用成功');
      }

      // 获取上一个页面的实例
      const pages = getCurrentPages();
      const prevPage = pages[pages.length - 2];

      // 调用上一个页面的 handleOutfitUpdate 方法
      if (prevPage && prevPage.handleOutfitUpdate) {
        console.log('saveOutfit: 调用上一个页面 handleOutfitUpdate', this.data.id ? '(编辑)' : '(新建)');
        prevPage.handleOutfitUpdate(res.data, !this.data.id);
      }

      // 显示成功提示
      Toast({
        context: this,
        selector: '#t-toast',
        message: this.data.id ? '保存成功' : '创建成功',
        icon: 'success'
      });

      // 保存成功后自动返回上一页
      setTimeout(() => {
        wx.navigateBack({
          delta: 1,
          success: () => {
            console.log('saveOutfit: 返回上一页成功');
          },
          fail: (error) => {
            console.error('saveOutfit: 返回上一页失败', error);
          }
        });
      }, 500); // 延迟500ms，让用户看到成功提示

    } catch (error) {
      console.error('saveOutfit: 保存失败', error);
      Toast({
        context: this,
        selector: '#t-toast',
        message: '保存失败',
        icon: 'error'
      });
    } finally {
      this.setData({ loading: false });
      console.log('saveOutfit: 保存操作结束，loading设置为false');
    }
  },

  // 显示衣物选择器
  showClothesSelector() {
    console.log('showClothesSelector: 尝试显示衣物选择器');
    this.setData({
      showClothesSelector: true,
      searchValue: '',
      currentSeason: '',
      currentCategory: '' // 确保打开衣物选择器时重置分类筛选
    });
    // 重新加载并过滤衣物列表
    this.loadAllClothes(); // 确保加载最新的 allClothes 并生成分类选项
    this.filterClothes(); // 初始过滤一次
    console.log('showClothesSelector: showClothesSelector:', this.data.showClothesSelector);
  },

  // 关闭衣物选择器
  closeClothesSelector() {
    this.setData({ showClothesSelector: false });
    console.log('closeClothesSelector: 关闭衣物选择器');
  },

  // 衣物选择器内的季节选择
  onClothesFilterSeasonChange(e) {
    const { value } = e.currentTarget.dataset;
    const newValue = value === this.data.currentSeason ? '' : value; // 切换选中状态，取消选中则设为空
    console.log('onClothesFilterSeasonChange: 选择季节过滤', newValue);
    this.setData({
      currentSeason: newValue
    });
    this.filterClothes(); // 季节变化后立即过滤
  },

  // 衣物选择器内的分类选择
  onClothesFilterCategorySelect(e) {
    const { value } = e.currentTarget.dataset;
    const newValue = value === this.data.currentCategory ? '' : value; // 切换选中状态，取消选中则设为空
    console.log('onClothesFilterCategorySelect: 选择分类过滤', newValue);
    this.setData({
      currentCategory: newValue
    });
    this.filterClothes(); // 分类变化后立即过滤
  }
}); 